package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


    @Resource
    IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        // 根据用户查询
        Blog blog = getById(id);
        queryBlogUserAndLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(this::queryBlogUserAndLiked);
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        String userId = UserHolder.getUser().getId().toString();
        // 1. 判断是否有已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        if (score == null) {
            // 2.没有点赞
            boolean ret = update().setSql("liked = liked+1").eq("id", id).update();
            if (ret) {
                stringRedisTemplate.opsForZSet().add(key, userId, System.currentTimeMillis());
            }
        } else {
            // 2.已经点赞
            boolean ret = update().setSql("liked = liked-1").eq("id", id).update();
            if (ret) {
                stringRedisTemplate.opsForZSet().remove(key, userId);
            }
        }
        return Result.ok();
    }

    @Override
    public Result isLikeBlog(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idsStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService.query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list()     // 注意查询
                .stream()
                .map(user -> {
                    UserDTO dto = new UserDTO();
                    BeanUtils.copyProperties(user, dto);
                    return dto;
                }).collect(Collectors.toList());

        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 保存
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        save(blog);

        // 查询粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 推动笔记id给所有粉丝
        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            String key = FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryFollow(Long last, Integer offset) {
        // 查询
        String userIdStr = UserHolder.getUser().getId().toString();
        String key = FEED_KEY + userIdStr;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, last, offset, 2);    // reverseRangeByScoreWithScores元素排序是按照score从大到小
        // rangeByScoreWithScores   元素排序是从小到大
        if (typedTuples==null || typedTuples.isEmpty()) {
            return Result.ok();
        }

        // 解析获取下一轮需要的参数
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = Long.MAX_VALUE;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            long id = Long.parseLong(typedTuple.getValue());
            ids.add(id);
            //
            long score = typedTuple.getScore().longValue(); // 转成long
            if (minTime == score) {
                os++;
            } else {
                minTime = score;
                os = 1;
            }
        }

        String idsStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        for (Blog blog : blogs) {
            queryBlogUserAndLiked(blog);
        }
        // 需要List, 偏移量, last
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        scrollResult.setList(blogs);
        return Result.ok(scrollResult);
    }

    private void queryBlogUserAndLiked(Blog blog) {
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Long authorId = blog.getUserId();

        User user = userService.getById(authorId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        // 用户可能没有登录
        UserDTO curUser = UserHolder.getUser();
        if (curUser ==null) {
            return;
        }
        Double score = stringRedisTemplate.opsForZSet().score(key, curUser.getId().toString());
        blog.setIsLike(score != null);
    }
}

